<template>
  <div class="orgMemberSelect">
    <el-row class="h100 w100" :gutter="40">
      <el-col :span="6" class="h100 treeContent">
        <customTree
          v-if="showLazyTree"
          ref="equipTree"
          :draggable="false"
          :nodeKey="nodeKey"
          @handleClickTree="backtreeData"
        ></customTree>
        <selectTree
          v-else
          :treeData="treeData"
          :defaultProps="defaultProps"
          :nodeKey="nodeKey"
          ref="tree2"
          :defaultExpandKeys="defaultExpandKeys"
          @handleClickTree="backtreeData"
        ></selectTree>
      </el-col>
      <el-col :span="18" class="h100 listContent">
        <memberList
          :selectConfig="selectConfig"
          ref="memerList"
          :isSeleteName="isSeleteName"
          @searchUserName="searchUserName"
          :chosedData="chosedData"
        ></memberList>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import memberList from "./memberList";
import selectTree from "./tree";
import customTree from "@/components/customTree/customTree";
import { getLeftUpperApi } from "@/api/equipmentLedger/equipmentManage";
import {
  queryOrgTree,
  queryOrgTreeAuth,
  queryUserList,
  queryRealNameUser,
  deviceClassifyTree, //设备分类树
} from "@/api/common";
import { getUserDataByOrg } from "@/api/systemManagement/userManagement.js";
import {
  locationTree, //位置树
} from "@/api/equipmentLedger/locationManage";

export default {
  components: { memberList, selectTree, customTree },
  props: {
    seleteSetting: Object,
    otherInfo: Object,
  },
  data() {
    return {
      selectConfig: {
        //是否单选
        radio: false,
        //中间栏位设置
        column: [
          {
            label: "用户名",
            prop: "name",
            width: 60,
          },
          {
            label: "职务",
            prop: "position",
            width: 60,
          },
          {
            label: "电话",
            prop: "phone",
            width: 100,
          },
        ],
        data: [],
      },
      userInfo: this.$store.getters.userInfo,
      chosedData: [],
      treeData: [],
      defaultExpandKeys: [],
      defaultProps: {
        label: "label",
        children: "children",
      },
      currentOrg: null,
      nodeKey: "",
      outOrg: "", //是否是外单位
    };
  },
  computed: {
    isSeleteName() {
      return ["orgmember", "realNameMember"].includes(
        this.selectConfig.seleteType
      );
    },
    showLazyTree() {
      return this.seleteSetting.seleteType == "device";
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      let { seleteType, chosedData, props, maxSelectNum, outOrg } =
        this.seleteSetting;
      this.outOrg = outOrg === undefined ? "" : outOrg;
      this.selectConfig = Object.assign(
        {},
        this.selectConfig,
        this.seleteSetting
      );
      this.defaultProps = Object.assign({}, this.defaultProps, props);
      this.chosedData = chosedData || [];
      //选择组织
      if (seleteType == "org") {
        //设置树的keys
        this.$set(this, "nodeKey", "organizationCode");
        this.getTreeInfo();
      }
      //选择组织
      else if (seleteType == "orgAuth" || seleteType == "realNameMember") {
        //设置树的keys
        this.$set(this, "nodeKey", "organizationCode");
        this.getAuthTreeInfo();
      }
      //选择人员
      else if (seleteType == "orgmember") {
        //设置树的keys
        this.$set(this, "nodeKey", "organizationCode");
        this.getTreeInfo();
      }
      //选择设备类型
      else if (seleteType == "deviceClassify") {
        this.$set(this, "nodeKey", "id");
        this.getClassifyTreeInfo(deviceClassifyTree);
      } else if (seleteType == "device") {
        this.getUserUpper();
        this.$set(this, "nodeKey", "id");
      } else if (seleteType == "location") {
        //选择位置
        this.$set(this, "nodeKey", "id");
        this.getLocationTreeInfo(locationTree);
      }
    },
    async getMajorEquipment() {
      await queryDispatchAlldept().then(res => {
        if (res.code == 200) {
          this.equipmentItem = res.data || [];
        }
      });
    },
    //默认展开到用户所在组织的节点
    getUserUpper() {
      getLeftUpperApi(this.userInfo.deptId).then(res => {
        this.$refs.equipTree.updataData(res.data, true);
      });
    },
    //点击树
    async backtreeData(data) {
      let { seleteType } = this.seleteSetting;
      this.currentOrg = data;
      //选择组织
      if (seleteType == "org" || seleteType == "orgAuth") {
        let newData = this.$utils.convert_tree_data([data]);
        newData.map((i) => ((i.name = i.name), (i.id = i.id)));
        if (seleteType == "orgAuth") {
          newData = newData.filter((i) => i.hasPermission);
        }

        this.$refs.memerList.setTableData(newData);
      }
      //选择人员
      else if (seleteType == "orgmember") {
        this.getTreeUser({ orgId: data.id });
      }
      //选择实名制人员
      else if (seleteType == "realNameMember") {
        this.getRealNameUser({ orgId: data.id });
      } else if (seleteType == "deviceClassify") {
        //选择设备分类树
        let newData = this.$utils.convert_tree_data([data]);
        newData.map((i) => ((i.name = i.name), (i.id = i.id)));
        //数据过滤
        if (this.selectConfig.filterMethod) {
          newData = await this.selectConfig.filterMethod(newData);
        }
        this.$refs.memerList.setTableData(newData);
      } else if (["device", "location"].includes(seleteType)) {
        //选择设备
        let newData = this.$utils.convert_tree_data([data]);
        if (seleteType == "device") {
          let arr = newData.filter((item) => {
            return item.isVirtual == 0;
          });
          this.$refs.memerList.setTableData(arr);
        } else {
          this.$refs.memerList.setTableData(newData);
        }
      }
    },
    getSeleteData() {
      let data = this.$refs.memerList.getSeleteData();
      return [...data];
    },
    //获取公司组织树信息
    getTreeInfo() {
      let form = {
        outOrg: this.outOrg, //是否是外单位
      };
      if (this.otherInfo) {
        form.parent = this.otherInfo.parentCode;
        queryOrgTree(form).then((res) => {
          let data = res.data;
          this.$refs.tree2.setTreeData(data);
        });
      } else {
        queryOrgTree(form).then((res) => {
          let data = res.data;
          this.$refs.tree2.setTreeData(data);
        });
      }
    },
    //获取公司组织树信息(权限)
    getAuthTreeInfo() {
      queryOrgTreeAuth().then((res) => {
        let data = res.data;
        this.$refs.tree2.setTreeData(data);
      });
    },
    //获取用户信息
    getTreeUser(data) {
      getUserDataByOrg(data).then((res) => {
        let data = res.data;
        this.$refs.memerList.setTableData(data);
      });
    },
    //获取用户信息
    getRealNameUser(data) {
      //实名制人员（劳务工）
      queryRealNameUser(data).then((res) => {
        let data = res.data;
        data.map(
          (i) => (
            (i.userName = i.staffName),
            (i.deptCode = i.orgId),
            (i.deptName = i.orgItem)
          )
        );
        this.$refs.memerList.setTableData(data);
      });
    },
    //获取设备分类树信息
    getClassifyTreeInfo(actionMethods) {
      //得到设备分类树的数据
      // deviceClassifyTree()
      actionMethods()
        .then((res) => {
          let zsjOrg = [];
          for (let i = 0; i < res.data.length; i++) {
            zsjOrg.push(res.data[i]);
          }
          this.orgCode = zsjOrg[0].id;
          this.defaultExpandKeys.push(zsjOrg[0].id);
          this.$refs.tree2.setTreeData(zsjOrg);
        })
        .catch((res) => {
          this.$refs.tree2.setTreeData([]);
          this.$message.error(`获取设备失败：${res.description}`);
        });
    },
    //获取位置数据
    getLocationTreeInfo() {
      //排除掉停用的节点status: "enabled"
      locationTree({ status: "enabled" })
        .then((res) => {
          let data = res.data;
          let arr = [];
          data.map((i) => {
            arr.push(i);
          });
          this.orgCode = arr[0].id;
          this.defaultExpandKeys.push(arr[0].id);
          this.$refs.tree2.setTreeData(arr);
        })
        .catch((res) => {
          this.$refs.tree2.setTreeData([]);
          this.$message.error(`获取位置数据失败：${res.description}`);
        });
    },
    //查询人员
    searchUserName(name) {
      let { seleteType } = this.seleteSetting;
      if (seleteType == "orgmember") {
        if (name) {
          this.getTreeUser({ name });
        } else if (this.currentOrg) {
          this.getTreeUser({ orgCode: this.currentOrg.organizationCode });
        }
      } else if (seleteType == "realNameMember") {
        if (name) {
          this.getRealNameUser({ name });
        } else if (this.currentOrg) {
          this.getRealNameUser({ orgId: this.currentOrg.organizationCode });
        }
      }
    },
  },
};
</script>
<style lang="less" scoped >
.orgMemberSelect {
  height: 500px;
  //border: 1px solid #ebebeb;
  width: 100%;
  min-width: 810px;
  padding: 0 10px;
  margin-bottom: 10px;
  /deep/ .list-table-search--item .search-btn {
    display: none;
  }
  /deep/ .list-table-search--item {
    .item-label {
      display: none;
    }
    width: 60%;
  }
  .treeContent {
    border: 1px solid #ebebeb;
    min-width: 180px;
  }
  .listContent {
    // min-width: 600px;
  }
  // /deep/ .search-up-down--btn {
  //   display: none;
  // }
}
</style>